package com.tobehonor.satokensample.loginsample.service;

import cn.dev33.satoken.stp.StpInterface;
import cn.hutool.core.collection.CollectionUtil;
import com.baomidou.mybatisplus.core.conditions.query.LambdaQueryWrapper;
import com.tobehonor.satokensample.mybatiscommon.entity.SysRole;
import com.tobehonor.satokensample.mybatiscommon.entity.SysUserRole;
import com.tobehonor.satokensample.mybatiscommon.service.ISysMenuService;
import com.tobehonor.satokensample.mybatiscommon.service.ISysRoleService;
import com.tobehonor.satokensample.mybatiscommon.service.ISysUserRoleService;
import com.tobehonor.satokensample.mybatiscommon.service.ISysUserService;
import org.springframework.stereotype.Component;

import java.util.ArrayList;
import java.util.List;
import java.util.Optional;
import java.util.stream.Collectors;

/**
 * 自定义权限验证接口扩展
 */
@Component
public class StpPermissionAuthService implements StpInterface {
    
    private final ISysMenuService sysMenuService;
    
    private final ISysRoleService sysRoleService;
    
    private final ISysUserService sysUserService;
    
    private final ISysUserRoleService sysUserRoleService;
    
    public StpPermissionAuthService(ISysMenuService sysMenuService, ISysRoleService sysRoleService,
            ISysUserService sysUserService, ISysUserRoleService sysUserRoleService) {
        this.sysMenuService = sysMenuService;
        this.sysRoleService = sysRoleService;
        this.sysUserService = sysUserService;
        this.sysUserRoleService = sysUserRoleService;
    }
    
    @Override
    public List<String> getPermissionList(Object loginId, String loginType) {
        
        return null;
    }
    
    @Override
    public List<String> getRoleList(Object loginId, String loginType) {
        List<SysUserRole> roleRelList = sysUserRoleService.list(
                new LambdaQueryWrapper<SysUserRole>().select(SysUserRole::getRoleId)
                        .eq(SysUserRole::getUserId, loginId));
        List<Long> roleIdList = roleRelList.stream().map(SysUserRole::getRoleId).collect(Collectors.toList());
        if (CollectionUtil.isEmpty(roleIdList)) {
            return new ArrayList<>();
        }
        List<SysRole> roleList = sysRoleService.list(
                new LambdaQueryWrapper<SysRole>().select(SysRole::getRoleCode).in(SysRole::getRoleId, roleIdList));
        
        return Optional.ofNullable(roleList).orElse(new ArrayList<>()).stream().map(SysRole::getRoleCode)
                .collect(Collectors.toList());
    }
}
